package com.tjhzzx.danfossNiagaraCore.command;

import com.tjhzzx.danfossNiagaraCore.alarm.AlarmManager;
import com.tjhzzx.danfossNiagaraCore.alarm.entities.AlarmClassItem;
import com.tjhzzx.danfossNiagaraCore.alarm.entities.AlarmClassMessage;
import com.tjhzzx.danfossNiagaraCore.alarm.entities.AlarmItem;
import com.tjhzzx.danfossNiagaraCore.alarm.entities.RealAlarmMessage;
import com.tjhzzx.danfossNiagaraCore.servlet.AbstractServletCommand;
import com.tjhzzx.danfossNiagaraCore.servlet.JSONResult;
import com.tridium.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.baja.alarm.BAlarmService;
import javax.baja.collection.BITable;
import javax.baja.naming.BOrd;
import javax.baja.security.BPermissions;
import javax.baja.security.PermissionException;
import javax.baja.sys.Sys;
import javax.baja.user.BUser;
import javax.baja.user.BUserService;
import javax.baja.web.WebOp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

public class AlarmSearchCommand extends AbstractServletCommand {

    private static final Logger LOGGER = Logger.getLogger(AlarmSearchCommand.class.getName());

    public void getAlarmClass(WebOp op, String queryString) throws Exception {
        Map<String, Object> params = resolveParams(queryString);
        List<AlarmClassItem> alarmClassItems = AlarmManager.getAlarmClassesOnConsoleRecipient();
        AlarmClassMessage result = new AlarmClassMessage();
        result.items = alarmClassItems;
        result.responseCode = AlarmClassMessage.OK;
        jsonResponse(result);
    }

    public void getTestBQL(WebOp op, String queryString) throws Exception {
        Map<String, Object> params = resolveParams(queryString);
        String bql = (String) params.get("b");
        String clazz = (String) params.get("c");
        BUserService localBUserService = (BUserService) Sys.getService(BUserService.TYPE);
        BUser localBUser = localBUserService.getAdmin();
        if (!localBUser.getEnabled()) {
            BUser[] arrayOfBUser = localBUserService.getChildren(BUser.class);
            for (int i = 0; i < arrayOfBUser.length; i++) {
                if ((arrayOfBUser[i].getEnabled()) && (arrayOfBUser[i].getPermissions().isSuperUser())) {
                    localBUser = arrayOfBUser[i];
                    break;
                }
            }
        }
        BAlarmService localBAlarmService = (BAlarmService)Sys.getService(BAlarmService.TYPE);
        try {
            localBUser.check(localBAlarmService.lookupAlarmClass(clazz), BPermissions.operatorRead);
        } catch (PermissionException localPermissionException) {
            localPermissionException.printStackTrace();
        }
        BITable tb = (BITable) BOrd.make(bql).get();
        jsonResponse(tb);
    }


    public void postRealAlarmData(WebOp op, String queryString) throws Exception {
        JSONResult pageResult = new JSONResult();
        Map<String, Object> params = resolveParams(queryString);
        String alarmClasses = (String) params.get("h");
        if (StringUtils.isBlank(alarmClasses)) {
            jsonResultResponse(JSONResult.error("告警查询参数'AlarmClass'配置错误"));
            return;
        }
        RealAlarmMessage request = new RealAlarmMessage();
        String[] alarmClassArray = alarmClasses.split("\\|\\|\\|");
        List<String> alarmStrings = new ArrayList<>();
        for (String alarmClass : alarmClassArray) {
            String[] clazz = alarmClass.split("\\|\\|");
            if (clazz != null && clazz.length == 2 && StringUtils.isNotBlank(clazz[0])
                    && StringUtils.isNotBlank(clazz[1])) {
                alarmStrings.add(clazz[1].substring(clazz[1].lastIndexOf('/') + 1));
            }
        }
        request.alarmClass = alarmStrings;
        List<AlarmItem> items = AlarmManager.getRealAlarmData(request);
        long pageNo = Long.parseLong((String) params.get("pageNo"));
        long pageSize = Long.parseLong((String) params.get("pageSize"));
        long total = items!=null?items.size():0;
        List<JSONObject> list = new ArrayList<>();
        if (items != null && items.size() > 0) {
            if(pageNo == -1) {
                pageSize = total;
                pageNo = 1;
            }
            long index = (pageNo - 1) * pageSize;
            for (long i = index; i < index + pageSize && i < items.size(); i++) {
                AlarmItem item = items.get((int) i);
                JSONObject row = new JSONObject();
                row.put("id", i);
                row.put("ord", item.ord);
                row.put("timestamp", item.timestamp);
                row.put("source", item.source);
                row.put("msgText", item.msgText);
                row.put("sourceState", item.sourceState);
                row.put("alarmClass", item.alarmClass);
                row.put("ackTime", item.ackTime);
                row.put("count", item.ackNum + "响应/" + item.unAckNum + "未响应");
                list.add(row);
            }
        }
        pageResult.add("total", total);
        pageResult.add("list", list);
        pageResult.setState(0);
        pageResult.setMessage("查询成功");
        jsonResultResponse(pageResult);
    }

    public void getRealAlarmDetail(WebOp op, String queryString) throws Exception {
        JSONResult pageResult = new JSONResult();
        Map<String, Object> params = resolveParams(queryString);
        String alarmOrd = (String) params.get("o");
        if (StringUtils.isBlank(alarmOrd)) {
            jsonResultResponse(JSONResult.error("告警查询参数'ord'配置错误"));
            return;
        }
        List<AlarmItem> items = AlarmManager.getRealAlarmDetail(alarmOrd);
        long pageNo = Long.parseLong((String) params.get("pageNo"));
        long pageSize = Long.parseLong((String) params.get("pageSize"));
        long total = items!=null?items.size():0;
        List<JSONObject> list = new ArrayList<>();
        if (items != null && items.size() > 0) {
            if(pageNo == -1) {
                pageSize = total;
                pageNo = 1;
            }
            long index = (pageNo - 1) * pageSize;
            for (long i = index; i < index + pageSize && i < items.size(); i++) {
                AlarmItem item = items.get((int) i);
                JSONObject row = new JSONObject();
                row.put("id", i);
                row.put("uuid", item.uuid);
                row.put("timestamp", item.timestamp);
                row.put("source", item.source);
                row.put("msgText", item.msgText);
                row.put("sourceState", item.sourceState);
                row.put("alarmClass", item.alarmClass);
                row.put("ackTime", item.ackTime);
                list.add(row);

            }
        }
        pageResult.add("total", total);
        pageResult.add("list", list);
        pageResult.setState(0);
        pageResult.setMessage("查询成功");
        jsonResultResponse(pageResult);
    }

    public void postAckAllAlarm(WebOp op, String queryString) throws Exception {
        Map<String, Object> params = resolveParams(queryString);
        String alarmOrd = (String) params.get("o");
        AlarmManager.ackAllAlarm(op.getUser().toString(), new String[]{alarmOrd}, true);
        JSONObject pageResult = new JSONObject();
        jsonResultResponse(JSONResult.success("响应成功"));
    }

    public void postAckEachAlarm(WebOp op, String queryString) throws Exception {
        Map<String, Object> params = resolveParams(queryString);
        String uuid = (String) params.get("u");
        AlarmManager.ackEachAlarm(op.getUser().toString(), new String[]{uuid}, true);
        jsonResultResponse(JSONResult.success("响应成功"));
    }
}
